//
//  CZNewFeatureViewController.swift
//  swift微博01
//
//  Created by 张文文 on 15/12/17.
//  Copyright © 2015年 张文文. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class CZNewFeatureViewController: UICollectionViewController {

    //流水布局
    private let layout = UICollectionViewFlowLayout()

    //AppDelegate会调用没有参数的构造函数
    init() {
    
        //调用负累的需要layout的构造函数
        super.init(collectionViewLayout : layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK : -属性
    /// 新特性界面数量
    private let ItemCount = 4
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    //准备collectionview的相关参数
    private func prepareCollectionView(){
    
        //注册cell
        self.collectionView!.registerClass(CZNewFeatureViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        //设置布局参数
        //一个item和屏幕一样大
        layout.itemSize = UIScreen.mainScreen().bounds.size
        //不要间距
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        //水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        //分页显示
        collectionView?.pagingEnabled = true
        //取消弹簧效果
        collectionView?.bounces = false
    }
       

    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        return ItemCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //去缓存池去查找
        //as类型转换，但是有可能转成功，也有可能转失败
        //as！ 表示一定能转成功 如果一旦转换失败  程序崩溃
        //as？ 表示有可能转成功 也有可能转不成功 返回值是一个可选
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZNewFeatureViewCell
    
        // Configure the cell
        cell.index = indexPath.item
    
        return cell
    }


    //collectionView 显示完毕时调用（在屏幕上看不到的时候会调用）
    //collectionView 听到某一页
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //collectionView 停到某一页 不实用indexpath 我们自己来获取现在在显示的cell indexpath
        let visitableIndexPath = collectionView.indexPathsForVisibleItems().last
        
        //判断是否是最后一个
        if visitableIndexPath?.item == ItemCount - 1{
        
            //获取visibleIndexPath 对应的cell
            let cell = collectionView.cellForItemAtIndexPath(visitableIndexPath!) as! CZNewFeatureViewCell
            
            //调用cell开始动画
            cell.startButtonAnimation()
        }
    }

}
//MARK - 自定义cell显示新特性界面
class CZNewFeatureViewCell : UICollectionViewCell{
    
    //gen根据不同的index来设置不同的图片
    var index = 0 {
    
        //属性监视器 当index发生变化时会调用
        didSet{
        
            //找到对应的图片 设置给背景视图
            backImageView.image = UIImage(named: "new_feature_\(index + 1)")
            //每当cell要显示之前都隐藏开始按钮
            startButton.hidden = true
        }
    }
    //系统会来调用
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: -开始按钮动画
    func startButtonAnimation(){
    
        //显示按钮
        startButton.hidden = false
        //设置开始按钮的scale
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        //使用uiview动画
        UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 3, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            //将开始按钮的transform的缩放设置成1（x，y）
//            self.startButton.transform = CGAffineTransformMakeScale(1, 1)
            //或者清空transfrom
            self.startButton.transform = CGAffineTransformIdentity
            }) {(_) -> Void in
                print("开始按钮动画完成")
                
        }
    }
    //MARK: -准备ui
    private func prepareUI(){
    
        //tian添加子控件tableViewCell 和 CollectionViewCell 添加子控件需要添加到contentView上面
        contentView.addSubview(backImageView)
        contentView.addSubview(startButton)
        //添加约束
        backImageView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        //bei背景填充父控件
        contentView.addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        //开始体验按钮 约束
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        
    }
    //MARK: - 懒加载 ，按钮会自动适配图片的大小
    //背景图片
    private lazy var backImageView : UIImageView = {
    
        let backImage = UIImageView(image: UIImage(named: "new_feature_1"))
        
        return backImage
    }()
    
    //开始按钮
    private lazy var startButton : UIButton = {
    
        let button = UIButton()
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        //设置按钮文字
        button.setTitle("开始体验", forState: UIControlState.Normal)
        //因为cell 复用  不能在船舰的时候来隐藏cell
        //button.hidden = true
        return button
    }()
}
